package com.hontech.bread.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Bitmap
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.hontech.bread.R
import com.hontech.bread.store.rootDir
import com.hontech.bread.utils.await
import com.hontech.bread.utils.hideSoftKey
import com.hontech.bread.utils.runCPU
import com.hontech.bread.utils.runIO
import com.hontech.bread.utils.stringById
import kotlinx.coroutines.CompletableDeferred
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

open class BaseActivity : AppCompatActivity() {


    companion object {
        lateinit var INSTANCE: BaseActivity
            private set

        fun parentView(): View {
            return INSTANCE.window.decorView
        }
    }

    private var permissionFuture: CompletableDeferred<Boolean>? = null

    private var actionDownTimestamp = 0L

    @SuppressLint("MissingSuperCall")
    override fun onConfigurationChanged(newConfig: Configuration) {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        INSTANCE = this
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            hideSoftKey(this)
            actionDownTimestamp = System.currentTimeMillis()
        } else if (ev.action == MotionEvent.ACTION_UP) {
            val current = System.currentTimeMillis()
            if ((current - actionDownTimestamp) > 2000) {
                actionDownTimestamp = current
//                runOnUi {
//                    runProg("${stringById(R.string.t1733460848_320)}", "${stringById(R.string.t1733460848_321)}") {
//                        viewCap()
//                    }
//                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    fun restart() {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        startActivity(intent)
        finish()
    }

    fun hideButton() {
        val decorView = window.decorView
        val uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                View.SYSTEM_UI_FLAG_FULLSCREEN
        decorView.systemUiVisibility = uiOptions
    }

    private suspend fun viewCap() {
        val view = window.decorView
        view.isDrawingCacheEnabled = true
        val bitmap = Bitmap.createBitmap(view.drawingCache)
        view.isDrawingCacheEnabled = false

        runIO {
            val file = File(rootDir, "img_${System.currentTimeMillis()}.png")
            val output = FileOutputStream(file)
            output.use {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
                output.flush()
            }
        }
    }

    suspend fun viewCap2(): ByteArray {
        val view = window.decorView
        view.isDrawingCacheEnabled = true
        val bitmap = Bitmap.createBitmap(view.drawingCache)
        view.isDrawingCacheEnabled = false

        return runIO {
            val output = ByteArrayOutputStream()
            output.use {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
                output.flush()
            }
            output.toByteArray()
        }
    }

    suspend fun requestPermission(permission: String) {
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
            return
        }
        if (PackageManager.PERMISSION_GRANTED == checkSelfPermission(permission)) {
            return
        }

        permissionFuture = CompletableDeferred()
        requestPermissions(arrayOf(permission), 0)
        val ret = permissionFuture!!.await(30 * 1000, stringById(R.string.t1733460848_322))
        if (!ret) {
            throw IllegalStateException("${stringById(R.string.t1733460848_323)} $permission")
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty()) {
            permissionFuture?.complete(grantResults[0] == PackageManager.PERMISSION_GRANTED)
        }
    }

    suspend fun requestImage(): ByteArray {
        val future = CompletableDeferred<InputStream>()

        val picker = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
            uri?.let {
                val input = contentResolver.openInputStream(uri)
                if (input == null) {
                    future.completeExceptionally(IllegalStateException("${stringById(R.string.t1733460848_324)}"))
                }
                future.complete(input!!)
            } ?: run {
                future.completeExceptionally(IllegalStateException("${stringById(R.string.t1733460848_325)}"))
            }
        }

        picker.launch(arrayOf("image/*"))

        val input = future.await()
        val data = runCPU {
            input.use {
                val buf = ByteArray(1024)
                val out = ByteArrayOutputStream()

                while (true) {
                    val n = input.read(buf)
                    if (n <= 0) {
                        break
                    }
                    out.write(buf, 0, n)
                }
                out.toByteArray()
            }
        }
        return data
    }
}


suspend fun readImage(): ByteArray {
    return BaseActivity.INSTANCE.requestImage()
}


